package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import service.OrderService;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderControllor {
    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //从Redis中获取缓存的验证码，key为手机号+RedisConstant.SENDTYPE_ORDER  比较
        String redisCode = jedisPool.getResource().get(map.get("telephone") + RedisMessageConstant.SENDTYPE_ORDER);
        if (redisCode==null || !redisCode.equals((String)map.get("validateCode"))){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Result result=null;
        try {
            //调用体检预约服务
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result= orderService.submit(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "预约失败");
        }
/*
        if(result.isFlag()){
            //预约成功，发送短信通知
            String orderDate = (String) map.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, (String)(map.get("telephone")), orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
*/

        return result;

    }

    //预约后展示的信息
    @RequestMapping("/findById")
    public Result findById( Integer id ){

        Map map= null;
        try {
            map = orderService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);

        }

        return new Result(true, MessageConstant.ORDER_SUCCESS, map );

    }
}
